{% extends "base.html" %}
{% block title %}{{title}} - Deal Detailed Information{% endblock %}
{% block deals %}
<!--CSS file (default YUI Sam Skin) -->
<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.7.0/build/button/assets/skins/sam/button.css" />
<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.7.0/build/container/assets/skins/sam/container.css" />        
<link type="text/css" rel="stylesheet"
      href="http://yui.yahooapis.com/2.7.0/build/datatable/assets/skins/sam/datatable.css">
<link rel="stylesheet" type="text/css"
      href="http://yui.yahooapis.com/2.7.0/build/paginator/assets/skins/sam/paginator.css"/>
<!-- Dependencies -->
<script type="text/javascript" src="http://yui.yahooapis.com/2.7.0/build/element/element-min.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.7.0/build/datasource/datasource-min.js"></script>
<!-- OPTIONAL: JSON Utility (for DataSource) -->
<script type="text/javascript" src="http://yui.yahooapis.com/2.7.0/build/json/json-min.js"></script>
<!-- OPTIONAL: Connection Manager (enables XHR for DataSource) -->
<script type="text/javascript" src="http://yui.yahooapis.com/2.7.0/build/connection/connection-min.js"></script>
<!-- OPTIONAL: Drag Drop (enables resizeable or reorderable columns) -->
<script type="text/javascript" src="http://yui.yahooapis.com/2.7.0/build/dragdrop/dragdrop-min.js"></script>
<!-- Source files -->
<script type="text/javascript" src="http://yui.yahooapis.com/2.7.0/build/datatable/datatable-min.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.7.0/build/paginator/paginator-min.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.7.0/build/button/button-min.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.7.0/build/container/container-min.js"></script>
<style type="text/css">
    .align_center {
        text-align: center !important;
    }
    .nowrap{
        white-space:nowrap;
    }
    .content_div{
        font-size:0.9em;
        margin:2px;
    }
    .title{
        font-size:1.1em;
        font-weight:bold;
    }
    label { display:block;float:left;clear:left;padding-bottom:5px }
    #comment{
        width:90%
    }
</style>
<script type="text/javascript">
    YAHOO.util.Event.addListener(window, "load", function() {
        YAHOO.comments.DynamicData = function() {
            // Column definitions
            var myColumnDefs = [ // sortable:true enables sorting
                {key:"check",resizeable:true,label:"",formatter:YAHOO.widget.DataTable.formatCheckbox,className:"align_center"},
                {key:"content", label:"Comments"},
                {key:"user.email", label:"Commented by", sortable:true},
                {key:"created_date", label:"Created Date", sortable:true,formatter:"date",className:"nowrap"}
            ];

            // DataSource instance
            var myDataSource = new YAHOO.util.DataSource("/json/getComments");
            myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
            myDataSource.responseSchema = {
                resultsList: "records",
                fields: [
                    {key:"content"},
                    {key:"created_date"},
                    {key:"key"},
                    {key:"user.email"}
                 ]
             };


            // DataTable configuration
            var myConfigs = {
                initialRequest: "?arg0=\"deal\"&arg1=\"{{deal.key}}\"&time=" + new Date().getTime(),  //'startIndex=0&results=25'
                dynamicData: true, // Enables dynamic server-driven data
                sortedBy : {key:"created_date", dir:YAHOO.widget.DataTable.CLASS_DESC} // Sets UI initial sort arrow
            };

            // DataTable instance
            var myDataTable = new YAHOO.widget.DataTable("comments_container", myColumnDefs, myDataSource, myConfigs);
            // Update totalRecords on the fly with value from server
            myDataTable.handleDataReturnPayload = function(oRequest, oResponse, oPayload) {
                oPayload.totalRecords = oResponse.meta.totalRecords;
                return oPayload;
            };

            // Selects any cell that receives a checkbox click
            myDataTable.subscribe("checkboxClickEvent", function(oArgs) {
                var elCheckbox = oArgs.target;
                var elRow = this.getTrEl(elCheckbox);
                if (elCheckbox.checked) {
                    this.selectRow(elRow);
                } else {
                    this.unselectRow(elRow);
                }
            });

            myDataTable.subscribe("cellClickEvent", myDataTable.onEventShowCellEditor);

            var selectedCommentIds = function(recordSet,selectedRows) {
                var comment_keys  = "comment_keys=";
                for (var x = 0, length=selectedRows.length; x < length; x++) {
                    var record =  recordSet.getRecord(selectedRows[x]);
                    comment_keys += record.getData().key;
                    if(x < length-1){
                        comment_keys+=",";
                    }
                }
                return comment_keys+"&comment_type=deal";
            };
            var deleteComments = function() {
                var selected = myDataTable.getSelectedRows();
                var rset = myDataTable.getRecordSet();
                if (selected.length > 0) {
                    YAHOO.util.Connect.asyncRequest('POST', '/json/deleteComments',
                    {
                        success: function (o) {
                            if (o.responseText == 'true') {
                                for (var x = 0; x < selected.length; x++) {
                                    myDataTable.deleteRow(rset.getRecordIndex(rset.getRecord(selected[x])));
                                }
                            } else {
                                alert(o.responseText);
                            }
                        },
                        failure: function (o) {
                            alert(o.statusText);
                        },
                        scope:this
                    }, selectedCommentIds(rset, selected)
                            );
                } else {
                    alert("Please select at least one Comment to delete.");
                }
            };

            YAHOO.util.Event.addListener("deleteComment", "click", deleteComments);

            // Define various event handlers for Dialog
            var handleSubmit = function() {
                var formObject = document.getElementById('comment_form');
                YAHOO.util.Connect.setForm(formObject); 
                YAHOO.util.Connect.asyncRequest('POST', '/json/addComment',
                {
                    success: function (o) {
                          var index = myDataTable.getRecordSet().getLength();
                          myDataTable.addRow(YAHOO.lang.JSON.parse(o.responseText), index);
                          YAHOO.comments.dialog1.hide();
                          YAHOO.util.Dom.get("comment_form").reset();
                    },
                    failure: function (o) {
                        alert(o.statusText);
                    },
                    scope:this
                });
            };
            var handleCancel = function() {
                this.cancel();
            };
            var handleFailure = function(o) {
                alert("Submission failed: " + o.status);
            };

            // Instantiate the Dialog
            YAHOO.comments.dialog1 = new YAHOO.widget.Dialog("dialog1",
                                    { width : "30em",
                                      fixedcenter : true,
                                      visible : false, 
                                      constraintoviewport : true,
                                      buttons : [ { text:"Submit", handler:handleSubmit, isDefault:true },
                                              { text:"Cancel", handler:handleCancel } ]
                                    });

            // Validate the entries in the form to require that both first and last name are entered
            YAHOO.comments.dialog1.validate = function() {
                var data = this.getData();
                if (data.comment == "") {
                    alert("Please enter your comment.");
                    return false;
                } else {
                    return true;
                }
            };

            // Render the Dialog
            YAHOO.comments.dialog1.render();

            var showDialog = function(){
                YAHOO.util.Dom.setStyle("dialog1","display","");
                YAHOO.comments.dialog1.show();
            };
            YAHOO.util.Event.addListener("addComment", "click", showDialog, YAHOO.comments.dialog1, true);

            return {
                ds: myDataSource,
                dt: myDataTable
            };

        }();
    });
</script>
<div>
    <div class="dealbox">
        <img border="0" align="right" src="{{deal.image}}"/>        
        <b>{{deal.title}}, </b>{{deal.pub_date}}<br/><br/>
        {{deal.content}}
        <br/><br/>
    </div>
    <div style="padding-bottom:5px;">
        {% if user_is_admin %}
        <button id="deleteComment">Delete</button>
        {% endif %}
        {% if user %}
        <button id="addComment">Add new Comment</button>
        {% endif %}
    </div>
     <div id="comments_container" width="100%">
    </div>
 </div>
<div id="dialog1" style="display:none;">
<div class="hd">Please enter your comment</div>
<div class="bd">
    <form method="POST" id="comment_form">
    <input type="hidden" id="deal_key" name="deal_key" value="{{deal.key}}">
    <input type="hidden" id="comment_type" name="comment_type" value="deal">
	<label for="comment">Comment:</label><textarea name="comment" id="comment"></textarea>
    </form>
</div>
</div>

{% endblock %}

